from collections import deque
from math import inf
from typing import *


class Solution:
    def maxResult(self, nums: List[int], k: int) -> int:
        q = deque()
        ans = 0
        for i in range(len(nums) - 1, -1, -1):
            num = nums[i]
            while q and q[-1][0] > i + k:
                q.pop()
            ans = num + (q[-1][1] if q else 0)
            while q and ans >= q[0][1]:
                q.popleft()
            q.appendleft([i, ans])
        return ans
